/**
 * Created by Administrator on 2018/7/3.
 */
//存放权限 是否 选择
$$scope.role={};
$$scope.authoEdit = {};
$$scope.authoEdit.projId = proId;
$$scope.authoEdit.authority = {};
//存放 权限 是否 被 注销
$$scope.authoEdit.originValue ={};
$$scope.authoEdit.baseInfo = {};
$$scope.authoEdit.baseInfo.userId = "";
$$scope.authoEdit.baseInfo.userName = "";
$$scope.authoEdit.baseInfo.projId = proId;
$$scope.authoEdit.baseInfo.descriptor = "";
//角色 可能 存在 兼岗
$$scope.authoEdit.baseInfo.role = "";
var staffColumns = [{
    id: 'userName',
    title: '人员姓名',
    width: 75,
    type: 'string',
    columnClass: 'text-center',
}, {
    id: 'positonName',
    title: '岗位名称',
    // width: 100,
    type: 'string',
    columnClass: 'text-center',
}, {
    id: 'userId',
    title: '入职时间',
    type: 'string',
    width: 150,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var date = new Date(record.createTime);
        var content = $.fn.dlshouwen.grid.tools.dateFormat(date, "yyyy-MM-dd hh:mm");
        return content;
    }
}, {
    id: 'operation',
    title: '操作',
    width: 70,
    type: 'string',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '';
        content += '<button class="btn btn-xs btn-success" onclick="select(\'' + record.userName + '\',\'' + record.userId + '\',\'' + record.positonName + '\');"><i class="icon-ok"></i>  选择</button>';
        return content;
    }
}];

$CertusFormAjax.ajax("findRelatedRole", {projectType: projectType}, function (res) {
    $$scope.roles = res.data;
    $CertusFormAjax.ajax("selectedRole",{tProjMemberId:tProjMemberId},function(res){
        if(res.data && res.data[0].trim()!=""){
            $$scope.role = {};
            for(var i in res.data){

                $$scope.role[res.data[i]]=true;
                //是否在 这里 做回显 让 角色 选择 的权限 直接 显示
                //todo
                $CertusFormAjax.ajax("pitchAuthority", {roleId: res.data[i],"projId":proId}, function (res) {
                    if (res.data) {
                        for (var index in res.data) {
                            $$scope.authoEdit.authority[index] = true;
                            nowOriginVlaueRole(index, "role");
                        }
                    }
                    $CertusFormAjax.ajax("yesAuthority",{projId:$res.data.proId,userId:$res.data.userId,yesOrNo:'NO'},function(res){
                        if (res.data) {
                            for (var index in res.data) {
                                $$scope.authoEdit.authority[index] = true;
                                nowOriginVlaue(index, "user");
                            }
                        }

                        $CertusFormAjax.ajax("yesAuthority1",{projId:$res.data.proId,userId:$res.data.userId,yesOrNo:'YES'},function(res){
                            if (res.data) {
                                for (var index in res.data) {
                                    $$scope.authoEdit.authority[index] = false;
                                    nowOriginVlaue(index, "user");
                                }
                            }
                        })

                    })
                })
            }
        }

    })
})
// $CertusJsonAjax.dataInit("userList", null, staffColumns, 'userDataGird', 'userGridToolBarContainer')




$(".searchButtom").on("click", function () {
    $("#userDataGird").empty();
    $("#userGridToolBarContainer").empty();
    if ($("#searchInputId").val() == "") {
        // $CertusJsonAjax.dataInit("userList", null, staffColumns, 'userDataGird', 'userGridToolBarContainer');
        $('#userDataGird').removeClass('n-pt-15');
        layer.msg("请输入....");
        return;
    }
    $CertusJsonAjax.dataInit("searchCompany", {"param": $("#searchInputId").val()}, staffColumns, 'userDataGird', 'userGridToolBarContainer',5)
    $('#userDataGird').addClass('n-pt-15');
});

/*初始化 权限 列表*/
$CertusFormAjax.ajax("queryProjAuthoriy", {projectType: projectType,projId:proId}, function (res) {
    $$scope.baseAuthoritys = res.data;
    //先加载 基础信息
    $CertusFormAjax.ajax("tProjMemberInfo",{tProjMemberId:tProjMemberId,projId:proId},function(res){
        //初始化姓名
        $("#empName").val(res.data.userName);
        $("#empId").val(res.data.userId);
        $$scope.authoEdit.baseInfo = res.data;
        $$scope.authoEdit.baseInfo.roleName = res.data.proRole;
        $$scope.authoEdit.baseInfo.projId = res.data.proId;

        //回显 角色名称

        $("#roleInputId").val(res.data.proRole.trim().replace(/\s/g,","));
        $res = res;
        //初始化
        //先测试 是否 需要 在 此处 做 角色权限 回显
        //做 人员 指定权限 回显

    })
})

function select(a, b, c) {
    $$scope.authoEdit.baseInfo.userId = b;
    $$scope.authoEdit.baseInfo.userName = a;
    $("#staffInputId").val(a + "(" + b + ")");
    $(".pdmiddle").hide();
}

/*权限选择框 变化 调用函数*/
$$scope.createChangeFunc = function ($event,a) {
    var code = $($event.target).attr("authorityCode");
    $$scope.authoEdit.authority[code] = a;
    nowOriginVlaue(code, 'user');
}

/*权限选择框  全选按钮*/
$$scope.allChangeFunc = function ($event, a) {

    var code = $($event.target).attr("authorityCode");
    //create
    var screate = code + "@@create";
    $$scope.authoEdit.authority[screate] = a;
    nowOriginVlaue(screate, 'user');
    //retrieve
    var screate = code + "@@retrieve";
    $$scope.authoEdit.authority[screate] = a;
    nowOriginVlaue(screate, 'user');
    //update
    var screate = code + "@@update";
    $$scope.authoEdit.authority[screate] = a;
    nowOriginVlaue(screate, 'user');
    //delete
    var screate = code + "@@delete";
    $$scope.authoEdit.authority[screate] = a;
    nowOriginVlaue(screate, 'user');
}

/*角色选择框 调用*/
$$scope.roleSelectedChange = function ($event, a, roleName) {

    if (a) {
        var roleId = $($event.target).attr("roleId");
        $("#roleInputId").val($("#roleInputId").val() + "," + roleName);
        $$scope.authoEdit.baseInfo.roleId += ","+roleId + ",";
        $$scope.authoEdit.baseInfo.roleName = $("#roleInputId").val();
        var regEx = /,+/g;
        $("#roleInputId").val($("#roleInputId").val().replace(regEx, ","));
        $CertusFormAjax.ajax("pitchAuthority", {roleId: roleId,projId:proId}, function (res) {
            if (res.data) {
                for (var index in res.data) {
                    $$scope.authoEdit.authority[index] = true;
                    nowOriginVlaueRole(index, "role");
                }
            }
        })
    } else {
        var roleId = $($event.target).attr("roleId");
        $$scope.authoEdit.baseInfo.roleId = $$scope.authoEdit.baseInfo.roleId.replace(roleId, "");
        $("#roleInputId").val($("#roleInputId").val().replace(roleName, ""));
        var regEx =/,+/g;
        $("#roleInputId").val($("#roleInputId").val().replace(regEx, ","));

        $CertusFormAjax.ajax("pitchAuthority", {roleId: roleId,projId:proId}, function (res) {
            if (res.data) {
                for (var index in res.data) {
                    $$scope.authoEdit.authority[index] = false;
                    nowOriginVlaueRole(index, "null");
                }
            }
        })
    }

    if ($("#roleInputId").val().indexOf(",") == 0) {
        $("#roleInputId").val($("#roleInputId").val().replace(",",""))
    }
    while( $("#roleInputId").val().length && $("#roleInputId").val().lastIndexOf(",") == $("#roleInputId").val().length - 1 &&  $("#roleInputId").val().length > 1){//|| $("#roleInputId").val().length > 0
        $("#roleInputId").val($("#roleInputId").val().substring(0,$("#roleInputId").val().length - 1))
    }
    $$scope.authoEdit.baseInfo.roleName = $("#roleInputId").val();
}

/*保存 按钮 调用方法*/
$$scope.saveProjectAuthority = function () {
    if(certusValidateNotnull()){
        // var length = $$scope.authoEdit.baseInfo.roleId.length;

        var reg = /\d+/;

        if($$scope.authoEdit.baseInfo.roleId){
            if (!reg.test($$scope.authoEdit.baseInfo.roleId)) {
                layer.msg("请添加至少一个，角色");
                return;
            }
            if($$scope.authoEdit.baseInfo.roleId.length){
                if($$scope.authoEdit.baseInfo.roleId.length > 200){
                    layer.msg("请不要 添加太多的角色");
                    return;
                }
            }
        }else{
            layer.msg("请添加至少一个，角色");
            return;
        }
        $$scope.authoEdit.userId = $("#empId").val();
        $$scope.authoEdit.userName = $("#empId").val();


        $CertusJsonAjax.ajax("saveProjAuthority", $$scope.authoEdit, function (res) {
            //调用 nodejs  执行操作记录变更

            if ("success" == res.data) {
                $$scope.authoEdit.operate = "change";
                $CertusJsonAjax.ajaxNode("member","projUserOperate",$$scope.authoEdit,function(res){
                    //刷新 操作记录 变更
                    layer.msg(res);
                })
                disProStaffAndEidtAuthority();
                layer.msg("保存成功");
            } else {
                layer.msg(res.data);
            }
        })
    }
}

/*utils 函数 */
function nowOriginVlaue(s, roleOrUser) {
    var ss = s + "-origin";
    var snow = s + "-now";
    if ($$scope.authoEdit.originValue[ss] == "" || $$scope.authoEdit.originValue[ss] == "null" || angular.isUndefined($$scope.authoEdit.originValue[ss])) {
        $$scope.authoEdit.originValue[ss] = roleOrUser;
        $$scope.authoEdit.originValue[snow] = roleOrUser;
    } else {
        $$scope.authoEdit.originValue[snow] = roleOrUser;
    }
}

function nowOriginVlaueRole(s, roleOrUser) {
    var ss = s + "-origin";
    var snow = s + "-now";
    $$scope.authoEdit.originValue[ss] = roleOrUser;
    $$scope.authoEdit.originValue[snow] = roleOrUser;
}

// 成员权限
// 员工姓名-客户自动补全
$CertusFormAjax.ajax("findSpUserList3", {}, function (response) {
    var nhlTeams = [];
    var data = response.data;
    for (var i = 0; i < data.length; i++) {
        var arr = {};

        arr.name = data[i].userName + "[" + data[i].positonName + "]";
        arr.id = data[i].userId;
        arr.userName = data[i].userName;
        nhlTeams.push(arr);
    }
    //自动补全
    var nhl = $.map(nhlTeams, function (obj) {

        return {
            value: obj.name,
            data: { category: obj.id,userName: obj.userName}
        };
    });
    // Initialize autocomplete with local lookup:
    $('#empName').devbridgeAutocomplete({
        lookup: nhl,
        minChars: 1,
        onSelect: function (suggestion) {

            $("#empId").val(suggestion.data.category);
            $("#userName").val(suggestion.data.userName);
            $$scope.authoEdit.baseInfo.userId = suggestion.data.category;
            $$scope.authoEdit.baseInfo.userName = suggestion.data.userName;
        },
        showNoSuggestionNotice: true,
        noSuggestionNotice: 'Sorry, no matching results'
    });
});